package com.dayouzi.crawler_monitor.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.dayouzi.crawler_monitor.base.exception.BusinessException;
import com.dayouzi.crawler_monitor.base.result.ResponseEnum;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
public class GoFastUtils {

    //go-fastdfs的上传地址
    private static final String UPLOAD_PATH = "http://192.168.1.223:8086/group6/upload";

    private static Gson gson = new Gson();

    /**
     * 上传文件
     * @param multipartFile
     * @return
     */
    public static String upload(MultipartFile multipartFile) {
        try {
            //获取文件名和后缀
            String type = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
            String fileName = UUID.randomUUID() + "." + type;
            byte[] bytes = multipartFile.getBytes();

            //上传
            HttpRequest request = HttpUtil.createPost(UPLOAD_PATH)
                    .header("Content-Type", "multipart/form-data")
                    .form("file", bytes, fileName)
                    .form("type", type)
                    .form("output", "json")
                    .timeout(10000);
            String body = request.execute().body();
            HashMap result = gson.fromJson(body, HashMap.class);
            return (String)result.get("url");
        } catch (Exception e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR);
        }
    }

}
